#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <fcntl.h>
#include <pthread.h>
#include <errno.h>
#include <sys/stat.h>
#include <limits.h>    // For PATH_MAX
#include <sys/epoll.h> // Added for epoll_ctl and EPOLL_CTL_DEL
#include "server.h"
#include "thread_pool.h"
#include "db.h"
#include "protocol.h"
#include "crypto/sm2_keyex.h"
#include "auth/sm3_auth.h"
#include "crypto/sm4_crypto.h"
#include "server/file_utils.h" // Include the new file utils header

// Define a constant for max plaintext block size, similar to client
// This is used for sizing the decryption buffer appropriately.
#define SERVER_DECRYPT_BUFFER_MAX_PLAINTEXT 4080
#define SERVER_UPLOAD_SUGGESTED_BLOCK_SIZE 4080

// 线程池全局变量
static thread_pool_t *server_thread_pool = NULL;

// Forward declaration
void process_client_event(void *arg);
static int set_nonblocking(int fd);         // Already exists
static uint32_t get_next_download_id(void); // Added prototype for get_next_download_id

// Forward declaration for reset function if defined later than first use (though usually static def comes before)
static void reset_client_download_state(client_context_t *ctx);
static void reset_client_upload_state(client_context_t *ctx); // Assuming this will be added/exists for symmetry

// Helper function to generate a cryptographically secure random IV
static int generate_secure_random_iv(unsigned char *iv_buf, size_t len)
{
    FILE *fp = fopen("/dev/urandom", "rb");
    if (!fp)
    {
        perror("fopen /dev/urandom");
        return -1;
    }
    size_t read_len = fread(iv_buf, 1, len, fp);
    fclose(fp);
    if (read_len != len)
    {
        fprintf(stderr, "Failed to read %zu bytes from /dev/urandom, got %zu\n", len, read_len);
        return -1;
    }
    return 0; // Success
}

// 设置socket为非阻塞模式
static int set_nonblocking(int fd)
{
    int flags = fcntl(fd, F_GETFL, 0);
    if (flags == -1)
    {
        perror("fcntl");
        return -1;
    }

    if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1)
    {
        perror("fcntl");
        return -1;
    }

    return 0;
}

// 初始化服务端
int server_init(int port)
{
    int server_fd;
    struct sockaddr_in server_addr;

    // 创建socket
    if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
    {
        perror("socket创建失败");
        return -1;
    }

    // 设置socket选项 - 地址重用
    int opt = 1;
    if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)) < 0)
    {
        perror("setsockopt失败");
        close(server_fd);
        return -1;
    }

    // 绑定地址
    memset(&server_addr, 0, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = INADDR_ANY;
    server_addr.sin_port = htons(port);

    if (bind(server_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0)
    {
        perror("绑定失败");
        close(server_fd);
        return -1;
    }

    // 监听连接
    if (listen(server_fd, 10) < 0)
    {
        perror("监听失败");
        close(server_fd);
        return -1;
    }

    // 创建线程池 - 4个最小线程，8个最大线程，100个最大任务队列
    server_thread_pool = thread_pool_create(4, 8, 100);
    if (server_thread_pool == NULL)
    {
        perror("线程池创建失败");
        close(server_fd);
        return -1;
    }

    return server_fd;
}

// 接受客户端连接
int server_accept(int server_fd)
{
    struct sockaddr_in client_addr;
    socklen_t client_len = sizeof(client_addr);

    int client_fd = accept(server_fd, (struct sockaddr *)&client_addr, &client_len);
    if (client_fd < 0)
    {
        // 非阻塞模式下可能会返回EAGAIN或EWOULDBLOCK
        if (errno != EAGAIN && errno != EWOULDBLOCK)
        {
            perror("accept失败");
        }
        return -1;
    }

    // 设置客户端socket为非阻塞模式
    if (set_nonblocking(client_fd) < 0)
    {
        close(client_fd);
        return -1;
    }

    // 打印客户端信息
    char client_ip[INET_ADDRSTRLEN];
    inet_ntop(AF_INET, &(client_addr.sin_addr), client_ip, INET_ADDRSTRLEN);
    printf("新客户端连接：%s:%d\n", client_ip, ntohs(client_addr.sin_port));

    return client_fd;
}

// This function replaces the old handle_client and the old client_task_t
// It is called by a thread from the pool when epoll signals an event on client_fd.
void process_client_event(void *arg)
{
    client_context_t *ctx = (client_context_t *)arg;
    if (!ctx)
    {
        fprintf(stderr, "[SERVER_ERROR] process_client_event called with NULL context.\n");
        return;
    }
    if (ctx->marked_for_close)
    {
        // Already marked, main loop will handle. Thread should exit.
        fprintf(stderr, "[SERVER_INFO] process_client_event: context for fd %d already marked for close.\n", ctx->client_fd);
        return;
    }

    uint8_t msg_type;
    uint16_t msg_seq;
    void *msg_data = NULL;
    uint32_t msg_len;

    int ret = recv_message(ctx->client_fd, &msg_type, &msg_seq, &msg_data, &msg_len);

    // Correctly handle PROT_ERR_RECV_TIMEOUT_WOULD_BLOCK (-10)
    if (ret == PROT_ERR_RECV_TIMEOUT_WOULD_BLOCK)
    {
        struct epoll_event event;
        event.data.ptr = ctx;
        event.events = EPOLLIN | EPOLLET | EPOLLONESHOT;
        if (epoll_ctl(ctx->epoll_fd, EPOLL_CTL_MOD, ctx->client_fd, &event) == -1)
        {
            perror("process_client_event: epoll_ctl EPOLL_CTL_MOD failed for PROT_ERR_RECV_TIMEOUT_WOULD_BLOCK");
            ctx->marked_for_close = 1;
        }
        if (msg_data) // Should be NULL if error occurred during header read
            free(msg_data);
        return;
    }

    // Handle other errors from recv_message (PROT_SUCCESS is 0)
    if (ret != PROT_SUCCESS)
    {
        fprintf(stderr, "[SERVER_RECV_ERROR] Error %d from recv_message (fd: %d). Marking for close.\n", ret, ctx->client_fd);
        // Based on the error, decide if it's a connection-closing error.
        // Most protocol errors from recv_message (other than timeout/would_block) are serious.
        ctx->marked_for_close = 1;
        if (msg_data)
            free(msg_data);
        return;
    }

    // If ret == PROT_SUCCESS, proceed to logging and the switch statement
    // fprintf(stderr, "[SERVER_MSG_DISPATCH] Received msg_type: %u, seq: %u, len: %u from fd: %d\\n",
    //         msg_type, msg_seq, msg_len, ctx->client_fd);

    // +++ DETAILED SWITCH DIAGNOSTIC LOGGING START +++
    uint8_t current_msg_type_for_switch = msg_type;
    // fprintf(stderr, "[SERVER_SWITCH_DEBUG] Value of msg_type entering switch: %u. MSG_TYPE_FILE_LIST_REQUEST is %d. fd: %d\\n",
    //         current_msg_type_for_switch, MSG_TYPE_FILE_LIST_REQUEST, ctx->client_fd);
    // +++ DETAILED SWITCH DIAGNOSTIC LOGGING END +++

    switch (current_msg_type_for_switch) // Use the saved variable for the switch
    {
    case MSG_TYPE_KEY_EXCHANGE:
    {
        // fprintf(stderr, "[SERVER_SWITCH_TRACE] Matched MSG_TYPE_KEY_EXCHANGE. fd: %d\\n", ctx->client_fd); // +++ TRACE
        fprintf(stdout, "服务端：接收到客户端 (fd: %d) 的SM2密钥交换请求。\n", ctx->client_fd);
        if (msg_data && msg_len >= sizeof(key_exchange_t))
        {
            key_exchange_t *key_ex = (key_exchange_t *)msg_data;
            memcpy(ctx->sm2_client_public_x, key_ex->public_key_x, sizeof(ctx->sm2_client_public_x));
            memcpy(ctx->sm2_client_public_y, key_ex->public_key_y, sizeof(ctx->sm2_client_public_y));
            fprintf(stdout, "服务端：已接收客户端 (fd: %d) 的SM2公钥。\n", ctx->client_fd);

            key_exchange_t response;
            fprintf(stdout, "服务端：准备发送服务端SM2公钥至客户端 (fd: %d)。\n", ctx->client_fd);
            sm2_get_public_key_coords(&ctx->sm2_server_key, response.public_key_x, sizeof(response.public_key_x), response.public_key_y, sizeof(response.public_key_y));

            if (send_message(ctx->client_fd, MSG_TYPE_KEY_EXCHANGE, msg_seq, &response, sizeof(response)) != 0)
            {
                fprintf(stderr, "发送密钥交换响应失败 (fd: %d)\n", ctx->client_fd);
                fprintf(stdout, "服务端：向客户端 (fd: %d) 发送SM2公钥失败。\n", ctx->client_fd);
                ctx->marked_for_close = 1;
                break;
            }
            fprintf(stdout, "服务端：已向客户端 (fd: %d) 发送服务端SM2公钥，准备使用SM2派生共享密钥。\n", ctx->client_fd);
            if (sm2_derive_shared_key(&ctx->sm2_server_key, ctx->sm2_client_public_x, sizeof(ctx->sm2_client_public_x), ctx->sm2_client_public_y, sizeof(ctx->sm2_client_public_y), ctx->shared_key, sizeof(ctx->shared_key)) != 0)
            {
                fprintf(stderr, "计算共享密钥失败 (fd: %d)\n", ctx->client_fd);
                fprintf(stdout, "服务端：与客户端 (fd: %d) 的SM2共享密钥派生失败。\n", ctx->client_fd);
                ctx->marked_for_close = 1;
                break;
            }
            ctx->key_exchange_done = 1;
            // printf("密钥交换完成 (fd: %d)\\n", ctx->client_fd);
            fprintf(stdout, "服务端：与客户端 (fd: %d) 的SM2共享密钥派生成功，密钥交换完成。\n", ctx->client_fd);
        }
        else
        {
            send_error_message(ctx->client_fd, msg_seq, ERR_INVALID_REQUEST, "无效的密钥交换请求");
        }
        break;
    }
    case MSG_TYPE_REGISTER_REQUEST:
    {
        // fprintf(stderr, "[SERVER_SWITCH_TRACE] Matched MSG_TYPE_REGISTER_REQUEST. fd: %d\\n", ctx->client_fd); // +++ TRACE
        if (!ctx->key_exchange_done)
        {
            send_error_message(ctx->client_fd, msg_seq, ERR_INVALID_STATE, "密钥交换未完成");
            break;
        }
        if (ctx->auth_done)
        {
            send_error_message(ctx->client_fd, msg_seq, ERR_INVALID_STATE, "用户已登录");
            break;
        }
        if (msg_data && msg_len == sizeof(register_request_t))
        {
            register_request_t *req = (register_request_t *)msg_data;
            register_response_t resp;
            memset(&resp, 0, sizeof(resp));
            printf("收到用户注册请求: 用户名='%s' (fd: %d)\n", req->username, ctx->client_fd);

            int registration_result = user_register(ctx->db, req->username, req->password);

            if (registration_result == 0)
            {
                resp.result = ERR_SUCCESS;
                resp.user_id = 0;
                printf("用户 '%s' 注册成功 (fd: %d).\n", req->username, ctx->client_fd);
            }
            else if (registration_result == -1)
            {
                resp.result = ERR_AUTH_FAILED;
                fprintf(stderr, "用户 '%s' 注册失败: 用户已存在或内部错误 (fd: %d, ret: %d).\n", req->username, ctx->client_fd, registration_result);
            }
            else
            {
                resp.result = ERR_INTERNAL_ERROR;
                fprintf(stderr, "用户 '%s' 注册失败: 内部错误 (fd: %d, ret: %d).\n", req->username, ctx->client_fd, registration_result);
            }

            if (send_message(ctx->client_fd, MSG_TYPE_REGISTER_RESPONSE, msg_seq, &resp, sizeof(resp)) != 0)
            {
                fprintf(stderr, "发送注册响应失败 (fd: %d)\n", ctx->client_fd);
                ctx->marked_for_close = 1;
            }
        }
        else
        {
            send_error_message(ctx->client_fd, msg_seq, ERR_INVALID_REQUEST, "无效的注册请求数据");
        }
        break;
    }
    case MSG_TYPE_AUTH_REQUEST:
    {
        // fprintf(stderr, "[SERVER_SWITCH_TRACE] Matched MSG_TYPE_AUTH_REQUEST. fd: %d\\n", ctx->client_fd); // +++ TRACE
        if (!ctx->key_exchange_done)
        {
            send_error_message(ctx->client_fd, msg_seq, ERR_INVALID_REQUEST, "请先完成密钥交换");
            break;
        }
        if (msg_data && msg_len >= sizeof(auth_request_t))
        {
            auth_request_t *auth_req = (auth_request_t *)msg_data;
            ctx->user_id = authenticate_user(ctx->db, auth_req->username, auth_req->password);
            auth_response_t auth_resp;
            if (ctx->user_id > 0)
            {
                auth_resp.result = ERR_SUCCESS;
                auth_resp.user_id = ctx->user_id;
                if (generate_auth_salt(ctx->session_token, sizeof(ctx->session_token)) != 0)
                {
                    send_error_message(ctx->client_fd, msg_seq, ERR_INTERNAL_ERROR, "生成会话令牌失败");
                    ctx->marked_for_close = 1;
                    break;
                }
                memcpy(auth_resp.token, ctx->session_token, sizeof(auth_resp.token));
                ctx->auth_done = 1;
                printf("用户 %s 认证成功 (fd: %d, user_id: %d)\n", auth_req->username, ctx->client_fd, ctx->user_id);
            }
            else
            {
                auth_resp.result = ERR_AUTH_FAILED;
                auth_resp.user_id = 0;
                memset(auth_resp.token, 0, sizeof(auth_resp.token));
                printf("用户 %s 认证失败 (fd: %d)\n", auth_req->username, ctx->client_fd);
            }
            if (send_message(ctx->client_fd, MSG_TYPE_AUTH_RESPONSE, msg_seq, &auth_resp, sizeof(auth_resp)) != 0)
            {
                fprintf(stderr, "发送认证响应失败 (fd: %d)\n", ctx->client_fd);
                ctx->marked_for_close = 1;
            }
        }
        else
        {
            send_error_message(ctx->client_fd, msg_seq, ERR_INVALID_REQUEST, "无效的认证请求");
        }
        break;
    }
    case MSG_TYPE_FILE_UPLOAD_REQUEST:
    {
        // fprintf(stderr, "[SERVER_SWITCH_TRACE] Matched MSG_TYPE_FILE_UPLOAD_REQUEST. fd: %d\\n", ctx->client_fd); // +++ TRACE
        fprintf(stdout, "服务端：接收到客户端 (fd: %d) 的文件上传请求 (MSG_TYPE_FILE_UPLOAD_REQUEST)。\n", ctx->client_fd);
        if (!ctx->auth_done)
        {
            // +++ PRE-SEND LOGGING FOR UPLOAD_REQUEST ERROR +++
            // fprintf(stderr, "[SERVER_SEND_PREP] fd: %d, About to send ERROR for UPLOAD_REQUEST (NOT_AUTHENTICATED): type=%u, seq=%u, error_code=%d, message='%s'\\n", ctx->client_fd, (unsigned int)MSG_TYPE_ERROR, msg_seq, ERR_NOT_AUTHENTICATED, "用户未认证");
            send_error_message(ctx->client_fd, msg_seq, ERR_NOT_AUTHENTICATED, "用户未认证");
            break;
        }
        if (ctx->upload_in_progress)
        {
            // +++ PRE-SEND LOGGING FOR UPLOAD_REQUEST ERROR +++
            // fprintf(stderr, "[SERVER_SEND_PREP] fd: %d, About to send ERROR for UPLOAD_REQUEST (UPLOAD_IN_PROGRESS): type=%u, seq=%u, error_code=%d, message='%s'\\n", ctx->client_fd, (unsigned int)MSG_TYPE_ERROR, msg_seq, ERR_UPLOAD_IN_PROGRESS, "另一个上传已在进行中");
            send_error_message(ctx->client_fd, msg_seq, ERR_UPLOAD_IN_PROGRESS, "另一个上传已在进行中");
            break;
        }
        // Reset previous upload state before starting a new one (safeguard)
        reset_client_upload_state(ctx);
        if (!msg_data || msg_len < sizeof(file_upload_request_t))
        {
            // +++ PRE-SEND LOGGING FOR UPLOAD_REQUEST ERROR +++
            // fprintf(stderr, "[SERVER_SEND_PREP] fd: %d, About to send ERROR for UPLOAD_REQUEST (INVALID_REQUEST_DATA_SIZE): type=%u, seq=%u, error_code=%d, message='%s'\\n", ctx->client_fd, (unsigned int)MSG_TYPE_ERROR, msg_seq, ERR_INVALID_REQUEST, "Invalid file upload request data.");
            send_error_message(ctx->client_fd, msg_seq, ERR_INVALID_REQUEST, "Invalid file upload request data.");
            add_audit_log(ctx->db, ctx->user_id, "UPLOAD_REQUEST_INVALID", NULL, ERR_INVALID_REQUEST);
            break;
        }
        file_upload_request_t *upload_req = (file_upload_request_t *)msg_data;
        // TODO: Validate session token: upload_req->token against ctx->session_token
        char path_for_permission_check[sizeof(upload_req->path) + 2];
        if (upload_req->path[0] == '/')
            strncpy(path_for_permission_check, upload_req->path, sizeof(path_for_permission_check) - 1);
        else
            snprintf(path_for_permission_check, sizeof(path_for_permission_check), "/%s", upload_req->path);
        path_for_permission_check[sizeof(path_for_permission_check) - 1] = '\0';

        fprintf(stdout, "服务端：对用户ID %d 请求上传文件 '%s' (路径: '%s') 进行权限检查...\n", ctx->user_id, upload_req->path, path_for_permission_check);
        int perm_check_result = check_file_permission(ctx->db, ctx->user_id, path_for_permission_check, OPERATION_WRITE);
        if (perm_check_result <= 0)
        {
            // +++ PRE-SEND LOGGING FOR UPLOAD_REQUEST ERROR +++
            // fprintf(stderr, "[SERVER_SEND_PREP] fd: %d, About to send ERROR for UPLOAD_REQUEST (PERMISSION_DENIED): type=%u, seq=%u, error_code=%d, message='%s'\\n", ctx->client_fd, (unsigned int)MSG_TYPE_ERROR, msg_seq, ERR_PERMISSION_DENIED, "Permission denied for file upload.");
            send_error_message(ctx->client_fd, msg_seq, ERR_PERMISSION_DENIED, "Permission denied for file upload.");
            fprintf(stdout, "服务端：用户ID %d 对文件 '%s' 的上传操作权限不足，请求被拒绝。\n", ctx->user_id, path_for_permission_check);
            add_audit_log(ctx->db, ctx->user_id, "UPLOAD_REQUEST_DENIED", path_for_permission_check, ERR_PERMISSION_DENIED);
            break;
        }

        fprintf(stdout, "服务端：用户ID %d 对文件 '%s' 的上传权限检查通过。准备接受请求...\n", ctx->user_id, path_for_permission_check);

        // Ensure base upload directory exists
        const char *base_upload_root = "/tmp/sfts_uploads";
        struct stat st_base_root = {0};
        if (stat(base_upload_root, &st_base_root) == -1)
        {
            if (mkdir(base_upload_root, 0755) == -1 && errno != EEXIST)
            {
                fprintf(stderr, "[SERVER_MKDIR_ERROR] Failed to create base upload directory '%s': %s (fd: %d)\n", base_upload_root, strerror(errno), ctx->client_fd);
                // +++ PRE-SEND LOGGING FOR UPLOAD_REQUEST ERROR +++
                // fprintf(stderr, "[SERVER_SEND_PREP] fd: %d, About to send ERROR for UPLOAD_REQUEST (MKDIR_BASE_FAILED): type=%u, seq=%u, error_code=%d, message='%s'\\n", ctx->client_fd, (unsigned int)MSG_TYPE_ERROR, msg_seq, ERR_INTERNAL_ERROR, "Server failed to prepare storage.");
                send_error_message(ctx->client_fd, msg_seq, ERR_INTERNAL_ERROR, "Server failed to prepare storage.");
                break;
            }
        }

        char user_upload_dir[PATH_MAX];
        snprintf(user_upload_dir, sizeof(user_upload_dir), "%s/%d", base_upload_root, ctx->user_id);
        struct stat st_user_dir = {0};
        if (stat(user_upload_dir, &st_user_dir) == -1)
        {
            if (mkdir(user_upload_dir, 0755) == -1 && errno != EEXIST)
            {
                fprintf(stderr, "[SERVER_MKDIR_ERROR] Failed to create user upload directory '%s': %s (fd: %d)\n", user_upload_dir, strerror(errno), ctx->client_fd);
                // +++ PRE-SEND LOGGING FOR UPLOAD_REQUEST ERROR +++
                // fprintf(stderr, "[SERVER_SEND_PREP] fd: %d, About to send ERROR for UPLOAD_REQUEST (MKDIR_USER_FAILED): type=%u, seq=%u, error_code=%d, message='%s'\\n", ctx->client_fd, (unsigned int)MSG_TYPE_ERROR, msg_seq, ERR_INTERNAL_ERROR, "Server failed to prepare user storage.");
                send_error_message(ctx->client_fd, msg_seq, ERR_INTERNAL_ERROR, "Server failed to prepare user storage.");
                break;
            }
        }

        const char *filename_only = strrchr(path_for_permission_check, '/');
        if (filename_only)
            filename_only++;
        else
            filename_only = path_for_permission_check; // Should not happen if path_for_permission_check starts with '/'

        // Ensure filename_only is not NULL and not empty before proceeding
        if (!filename_only || *filename_only == '\0')
        {
            fprintf(stderr, "[SERVER_ERROR] Invalid filename derived for upload (fd: %d, path: %s)\n", ctx->client_fd, path_for_permission_check);
            // +++ PRE-SEND LOGGING FOR UPLOAD_REQUEST ERROR +++
            // fprintf(stderr, "[SERVER_SEND_PREP] fd: %d, About to send ERROR for UPLOAD_REQUEST (INVALID_FILENAME): type=%u, seq=%u, error_code=%d, message='%s'\\n", ctx->client_fd, (unsigned int)MSG_TYPE_ERROR, msg_seq, ERR_INVALID_REQUEST, "Invalid file path for upload.");
            send_error_message(ctx->client_fd, msg_seq, ERR_INVALID_REQUEST, "Invalid file path for upload.");
            add_audit_log(ctx->db, ctx->user_id, "UPLOAD_REQUEST_FAILED", path_for_permission_check, ERR_INVALID_REQUEST);
            break;
        }

        snprintf(ctx->current_upload_server_path, sizeof(ctx->current_upload_server_path), "%s/%s", user_upload_dir, filename_only);
        ctx->upload_file_ptr = fopen(ctx->current_upload_server_path, "wb");
        if (!ctx->upload_file_ptr)
        {
            fprintf(stderr, "[SERVER_FOPEN_ERROR] Failed to open file '%s' for writing: %s (fd: %d)\n", ctx->current_upload_server_path, strerror(errno), ctx->client_fd);
            // +++ PRE-SEND LOGGING FOR UPLOAD_REQUEST ERROR +++
            // fprintf(stderr, "[SERVER_SEND_PREP] fd: %d, About to send ERROR for UPLOAD_REQUEST (FOPEN_FAILED): type=%u, seq=%u, error_code=%d, message='%s'\\n", ctx->client_fd, (unsigned int)MSG_TYPE_ERROR, msg_seq, ERR_INTERNAL_ERROR, "Server failed to prepare for file upload.");
            send_error_message(ctx->client_fd, msg_seq, ERR_INTERNAL_ERROR, "Server failed to prepare for file upload.");
            add_audit_log(ctx->db, ctx->user_id, "UPLOAD_REQUEST_FAILED", path_for_permission_check, ERR_INTERNAL_ERROR);
            break;
        }
        ctx->upload_in_progress = 1;
        ctx->expected_upload_size = upload_req->size;
        ctx->received_upload_size = 0;
        // Generate a unique upload ID. For simplicity, using a placeholder.
        // In a real system, this should be a unique ID generator.
        ctx->current_upload_id = (uint32_t)time(NULL) ^ (uint32_t)getpid() ^ (uint32_t)ctx->client_fd;
        ctx->iv_received_for_upload = 0;
        memset(ctx->upload_session_iv, 0, SM4_IV_SIZE); // Clear IV for new upload

        file_upload_response_t upload_resp;
        upload_resp.result = ERR_SUCCESS;
        upload_resp.upload_id = ctx->current_upload_id;
        upload_resp.block_size = SERVER_UPLOAD_SUGGESTED_BLOCK_SIZE; // Inform client of preferred block size for data

        // +++ PRE-SEND LOGGING FOR UPLOAD_REQUEST SUCCESS RESPONSE +++
        // fprintf(stderr, "[SERVER_SEND_PREP] fd: %d, About to send SUCCESS for UPLOAD_REQUEST: type=%u, seq=%u, upload_id=%u, block_size=%u\\n", ctx->client_fd, (unsigned int)MSG_TYPE_FILE_UPLOAD_RESPONSE, msg_seq, upload_resp.upload_id, upload_resp.block_size);
        if (send_message(ctx->client_fd, MSG_TYPE_FILE_UPLOAD_RESPONSE, msg_seq, &upload_resp, sizeof(upload_resp)) != 0)
        {
            fprintf(stderr, "Failed to send upload response (fd: %d)\n", ctx->client_fd);
            fclose(ctx->upload_file_ptr);
            ctx->upload_file_ptr = NULL;
            ctx->upload_in_progress = 0;
            // Audit log for UPLOAD_REQUEST_FAILED might be appropriate if we consider this part of setup.
            // However, client didn't get the go-ahead.
            ctx->marked_for_close = 1;
        }
        else
        {
            add_audit_log(ctx->db, ctx->user_id, "UPLOAD_REQUEST_ACCEPTED", path_for_permission_check, ERR_SUCCESS);
            fprintf(stdout, "服务端：文件上传请求 '%s' (用户ID: %d, 上传ID: %u) 已接受，响应已发送给客户端 (fd: %d)。\n", path_for_permission_check, ctx->user_id, ctx->current_upload_id, ctx->client_fd);
        }
        break;
    }
    case MSG_TYPE_FILE_UPLOAD_DATA:
    {
        // fprintf(stderr, "[SERVER_SWITCH_TRACE] Matched MSG_TYPE_FILE_UPLOAD_DATA. fd: %d\\n", ctx->client_fd); // +++ TRACE
        fprintf(stdout, "服务端：接收到客户端 (fd: %d) 发送的文件上传数据块。\n", ctx->client_fd);
        if (!ctx->auth_done || ctx->user_id <= 0 || !ctx->upload_in_progress || !ctx->upload_file_ptr)
        {
            send_error_message(ctx->client_fd, msg_seq, ctx->auth_done ? ERR_INVALID_STATE : ERR_AUTH_FAILED, "Invalid state for upload data.");
            break;
        }
        if (!msg_data || msg_len < offsetof(file_upload_data_t, data))
        {
            send_error_message(ctx->client_fd, msg_seq, ERR_INVALID_REQUEST, "Invalid file upload data message structure.");
            break;
        }
        file_upload_data_t *data_block = (file_upload_data_t *)msg_data;
        uint32_t actual_payload_size_from_msg = msg_len - offsetof(file_upload_data_t, data);
        if (data_block->data_len == 0 || data_block->data_len > actual_payload_size_from_msg)
        {
            send_error_message(ctx->client_fd, msg_seq, ERR_INVALID_REQUEST, "Invalid data_len in upload data message.");
            break;
        }
        const unsigned char *received_sm4_payload = data_block->data;
        size_t received_sm4_payload_len = data_block->data_len;
        unsigned char decrypted_buffer[SERVER_DECRYPT_BUFFER_MAX_PLAINTEXT + SM4_BLOCK_SIZE];
        size_t decrypted_data_len = 0;
        const unsigned char *data_to_decrypt = NULL;
        size_t len_to_decrypt = 0;
        if (!ctx->iv_received_for_upload)
        {
            if (data_block->block_seq != 0)
            {
                send_error_message(ctx->client_fd, msg_seq, ERR_INVALID_STATE, "IV not received for upload.");
                break;
            }
            if (received_sm4_payload_len < SM4_IV_SIZE)
            {
                send_error_message(ctx->client_fd, msg_seq, ERR_INVALID_REQUEST, "Invalid first data block (too short for IV).");
                break;
            }
            memcpy(ctx->upload_session_iv, received_sm4_payload, SM4_IV_SIZE);
            ctx->iv_received_for_upload = 1;
            data_to_decrypt = received_sm4_payload + SM4_IV_SIZE;
            len_to_decrypt = received_sm4_payload_len - SM4_IV_SIZE;
            fprintf(stdout, "服务端：客户端 (fd: %d) 发送的是首个数据块，已提取SM4-CBC模式的IV。待解密数据长度: %zu B。\n", ctx->client_fd, len_to_decrypt);
        }
        else
        {
            data_to_decrypt = received_sm4_payload;
            len_to_decrypt = received_sm4_payload_len;
            fprintf(stdout, "服务端：客户端 (fd: %d) 发送的是后续数据块。待解密数据长度: %zu B。\n", ctx->client_fd, len_to_decrypt);
        }
        if (len_to_decrypt > 0)
        {
            decrypted_data_len = sizeof(decrypted_buffer);
            fprintf(stdout, "服务端：准备使用SM4-CBC模式解密来自客户端 (fd: %d) 的文件数据块。\n", ctx->client_fd);
            if (sm4_cbc_decrypt_data(data_to_decrypt, len_to_decrypt, ctx->shared_key, ctx->upload_session_iv, decrypted_buffer, &decrypted_data_len) != 0)
            {
                send_error_message(ctx->client_fd, msg_seq, ERR_CRYPTO_ERROR, "Server failed to decrypt uploaded data.");
                fprintf(stdout, "服务端：SM4解密客户端 (fd: %d) 数据块失败。\n", ctx->client_fd);
                fclose(ctx->upload_file_ptr);
                ctx->upload_file_ptr = NULL;
                ctx->upload_in_progress = 0;
                ctx->iv_received_for_upload = 0;
                break;
            }
        }
        fprintf(stdout, "服务端：SM4解密客户端 (fd: %d) 数据块成功，得到明文数据长度: %zu B。\n", ctx->client_fd, decrypted_data_len);

        if (decrypted_data_len > 0)
        {
            size_t bytes_written = fwrite(decrypted_buffer, 1, decrypted_data_len, ctx->upload_file_ptr);
            if (bytes_written != decrypted_data_len)
            {
                send_error_message(ctx->client_fd, msg_seq, ERR_INTERNAL_ERROR, "Server failed to write uploaded data.");
                fclose(ctx->upload_file_ptr);
                ctx->upload_file_ptr = NULL;
                ctx->upload_in_progress = 0;
                ctx->iv_received_for_upload = 0;
                break;
            }
            ctx->received_upload_size += bytes_written;
        }
        file_upload_data_response_t data_ack;
        data_ack.upload_id = data_block->upload_id;
        data_ack.block_seq = data_block->block_seq;
        data_ack.result = ERR_SUCCESS;
        fprintf(stdout, "服务端：文件数据块 (来自 fd: %d, upload_id: %u, block_seq: %u) 处理完毕，向客户端发送确认。\n", ctx->client_fd, data_block->upload_id, data_block->block_seq);
        if (send_message(ctx->client_fd, MSG_TYPE_FILE_UPLOAD_DATA_RESPONSE, msg_seq, &data_ack, sizeof(data_ack)) != 0)
        {
            ctx->marked_for_close = 1; // Error sending ack, client might be gone or desynced.
        }
        if (ctx->received_upload_size >= ctx->expected_upload_size)
        {
            fclose(ctx->upload_file_ptr);
            ctx->upload_file_ptr = NULL;
            ctx->upload_in_progress = 0;
            memset(ctx->current_upload_server_path, 0, sizeof(ctx->current_upload_server_path));
            ctx->expected_upload_size = 0;
            ctx->received_upload_size = 0;
            ctx->current_upload_id = 0;
            ctx->iv_received_for_upload = 0;
            add_audit_log(ctx->db, ctx->user_id, "UPLOAD_COMPLETED", strrchr(ctx->current_upload_server_path, '/') ? strrchr(ctx->current_upload_server_path, '/') + 1 : ctx->current_upload_server_path, ERR_SUCCESS);
            fprintf(stdout, "服务端：来自客户端 (fd: %d) 的文件 '%s' 已全部接收并成功完成SM4解密。上传ID: %u。\n", ctx->client_fd, ctx->current_upload_server_path, data_block->upload_id);
        }
        break;
    }
    case MSG_TYPE_FILE_LIST_REQUEST:
    {
        // fprintf(stderr, "[SERVER_SWITCH_TRACE] Matched MSG_TYPE_FILE_LIST_REQUEST. fd: %d\\n", ctx->client_fd); // +++ TRACE
        if (!ctx->auth_done)
        {
            send_error_message(ctx->client_fd, msg_seq, ERR_AUTH_FAILED, "请先完成认证");
            break;
        }
        if (msg_data && msg_len >= sizeof(file_list_request_t))
        {
            file_list_request_t *list_req = (file_list_request_t *)msg_data;
            if (memcmp(list_req->token, ctx->session_token, sizeof(ctx->session_token)) != 0)
            {
                send_error_message(ctx->client_fd, msg_seq, ERR_AUTH_FAILED, "无效的会话令牌");
                break;
            }
            char user_base_upload_dir_list[PATH_MAX];                // Renamed to avoid conflict
            const char *base_upload_root_list = "/tmp/sfts_uploads"; // Renamed for clarity
            struct stat st_base_root_list = {0};

            if (stat(base_upload_root_list, &st_base_root_list) == -1)
            {
                if (mkdir(base_upload_root_list, 0755) == -1 && errno != EEXIST)
                {
                    fprintf(stderr, "[SERVER_MKDIR_ERROR] Failed to create base directory for list '%s': %s (fd: %d)\n", base_upload_root_list, strerror(errno), ctx->client_fd);
                    send_error_message(ctx->client_fd, msg_seq, ERR_INTERNAL_ERROR, "服务器未能准备用户目录 (base).");
                    break;
                }
            }
            snprintf(user_base_upload_dir_list, sizeof(user_base_upload_dir_list), "%s/%d", base_upload_root_list, ctx->user_id);
            struct stat st_user_dir_list = {0};
            if (stat(user_base_upload_dir_list, &st_user_dir_list) == -1)
            {
                if (mkdir(user_base_upload_dir_list, 0755) == -1 && errno != EEXIST)
                {
                    fprintf(stderr, "[SERVER_MKDIR_ERROR] Failed to create user directory for list '%s': %s (fd: %d)\n", user_base_upload_dir_list, strerror(errno), ctx->client_fd);
                    send_error_message(ctx->client_fd, msg_seq, ERR_INTERNAL_ERROR, "服务器未能准备用户目录.");
                    break;
                }
            }

            file_entry_t *actual_file_entries = NULL;
            int file_count = 0;
            // Use user_base_upload_dir_list for the path to scan
            if (list_uploaded_files_for_user(ctx->db, ctx->user_id, user_base_upload_dir_list, list_req->path, &actual_file_entries, &file_count) != 0)
            {
                send_error_message(ctx->client_fd, msg_seq, ERR_INTERNAL_ERROR, "获取文件列表失败.");
                if (actual_file_entries)
                    free(actual_file_entries);
                break;
            }
            size_t resp_payload_size = file_count * sizeof(file_entry_t);
            size_t total_resp_size = sizeof(uint32_t) + resp_payload_size;
            unsigned char *resp_data = malloc(total_resp_size);
            if (!resp_data)
            {
                send_error_message(ctx->client_fd, msg_seq, ERR_INTERNAL_ERROR, "内存分配失败");
                if (actual_file_entries)
                    free(actual_file_entries);
                break;
            }
            *((uint32_t *)resp_data) = file_count;
            if (file_count > 0 && actual_file_entries)
            {
                memcpy(resp_data + sizeof(uint32_t), actual_file_entries, resp_payload_size);
            }
            if (send_message(ctx->client_fd, MSG_TYPE_FILE_LIST_RESPONSE, msg_seq, resp_data, total_resp_size) != 0)
            {
                ctx->marked_for_close = 1;
            }
            free(resp_data);
            if (actual_file_entries)
                free(actual_file_entries);
        }
        else
        {
            // +++ PRE-SEND LOGGING FOR LIST_REQUEST ERROR +++
            // fprintf(stderr, "[SERVER_SEND_PREP] fd: %d, About to send ERROR for LIST_REQUEST: type=%u, seq=%u, error_code=%d, message='%s'\\n",
            //         ctx->client_fd, (unsigned int)MSG_TYPE_ERROR, msg_seq, ERR_INVALID_REQUEST, "无效的文件列表请求数据.");
            send_error_message(ctx->client_fd, msg_seq, ERR_INVALID_REQUEST, "无效的文件列表请求数据.");
        }
        break;
    }
    case MSG_TYPE_FILE_DELETE_REQUEST:
    {
        // fprintf(stderr, "[SERVER_SWITCH_TRACE] Matched MSG_TYPE_FILE_DELETE_REQUEST. fd: %d\\n", ctx->client_fd); // +++ TRACE
        if (!ctx->auth_done || ctx->user_id <= 0)
        {
            send_error_message(ctx->client_fd, msg_seq, ERR_AUTH_FAILED, "User not authenticated for delete.");
            add_audit_log(ctx->db, ctx->user_id > 0 ? ctx->user_id : -1, "DELETE_REQUEST_DENIED", NULL, ERR_AUTH_FAILED);
            break;
        }
        if (!msg_data || msg_len < sizeof(file_delete_request_t))
        {
            send_error_message(ctx->client_fd, msg_seq, ERR_INVALID_REQUEST, "Invalid file delete request data.");
            add_audit_log(ctx->db, ctx->user_id, "DELETE_REQUEST_INVALID", NULL, ERR_INVALID_REQUEST);
            break;
        }
        file_delete_request_t *del_req = (file_delete_request_t *)msg_data;
        if (memcmp(del_req->token, ctx->session_token, sizeof(ctx->session_token)) != 0)
        {
            send_error_message(ctx->client_fd, msg_seq, ERR_AUTH_FAILED, "Invalid session token for delete.");
            add_audit_log(ctx->db, ctx->user_id, "DELETE_REQUEST_DENIED", del_req->path, ERR_AUTH_FAILED);
            break;
        }
        char path_for_permission_check[PATH_MAX];
        if (del_req->path[0] == '/')
            strncpy(path_for_permission_check, del_req->path, sizeof(path_for_permission_check) - 1);
        else
            snprintf(path_for_permission_check, sizeof(path_for_permission_check), "/%s", del_req->path);
        path_for_permission_check[sizeof(path_for_permission_check) - 1] = '\0';

        int perm_check_result = check_file_permission(ctx->db, ctx->user_id, path_for_permission_check, OPERATION_DELETE);
        if (perm_check_result <= 0)
        {
            send_error_message(ctx->client_fd, msg_seq, ERR_PERMISSION_DENIED, "Permission denied for file delete.");
            add_audit_log(ctx->db, ctx->user_id, "DELETE_REQUEST_DENIED", path_for_permission_check, ERR_PERMISSION_DENIED);
            break;
        }

        const char *base_upload_root_del = "/tmp/sfts_uploads";
        struct stat st_base_root_del = {0};
        if (stat(base_upload_root_del, &st_base_root_del) == -1)
        {
            if (mkdir(base_upload_root_del, 0755) == -1 && errno != EEXIST)
            {
                // Log error but might not need to send error to client if user dir creation fails later
                fprintf(stderr, "[SERVER_MKDIR_ERROR] Failed to create base directory for delete '%s': %s (fd: %d)\n", base_upload_root_del, strerror(errno), ctx->client_fd);
            }
        }

        char user_upload_dir[PATH_MAX];
        snprintf(user_upload_dir, sizeof(user_upload_dir), "%s/%d", base_upload_root_del, ctx->user_id);
        // No need to create user_upload_dir for delete, if it doesn't exist, unlink will fail anyway.
        // struct stat st_user_dir_del = {0};
        // if (stat(user_upload_dir, &st_user_dir_del) == -1) {
        //      if (mkdir(user_upload_dir, 0755) == -1 && errno != EEXIST) {
        //         fprintf(stderr, "[SERVER_MKDIR_ERROR] Failed to create user directory for delete '%s': %s (fd: %d)\n", user_upload_dir, strerror(errno), ctx->client_fd);
        //         send_error_message(ctx->client_fd, msg_seq, ERR_INTERNAL_ERROR, "Server failed to prepare user storage for delete.");
        //         break;
        //     }
        // }

        const char *filename_only = strrchr(path_for_permission_check, '/');
        if (filename_only)
            filename_only++;
        else
        {
            filename_only = path_for_permission_check;
            if (filename_only[0] == '/' && strlen(filename_only) > 1)
                filename_only++;
            else if (filename_only[0] == '/' && strlen(filename_only) == 1)
                filename_only = "";
        }
        if (strlen(filename_only) == 0 || strcmp(filename_only, ".") == 0 || strcmp(filename_only, "..") == 0)
        {
            send_error_message(ctx->client_fd, msg_seq, ERR_INVALID_PATH, "Invalid filename for delete.");
            add_audit_log(ctx->db, ctx->user_id, "DELETE_REQUEST_INVALID", path_for_permission_check, ERR_INVALID_PATH);
            break;
        }
        char physical_file_path[PATH_MAX];
        snprintf(physical_file_path, sizeof(physical_file_path), "%s/%s", user_upload_dir, filename_only);
        if (unlink(physical_file_path) == 0)
        {
            file_delete_response_t del_resp;
            del_resp.result = ERR_SUCCESS;
            // +++ PRE-SEND LOGGING FOR DELETE_REQUEST SUCCESS +++
            // fprintf(stderr, "[SERVER_SEND_PREP] fd: %d, About to send SUCCESS for DELETE_REQUEST: type=%u, seq=%u\\n",
            //         ctx->client_fd, (unsigned int)MSG_TYPE_FILE_DELETE_RESPONSE, msg_seq);
            if (send_message(ctx->client_fd, MSG_TYPE_FILE_DELETE_RESPONSE, msg_seq, &del_resp, sizeof(del_resp)) != 0)
            {
                ctx->marked_for_close = 1;
            }
            add_audit_log(ctx->db, ctx->user_id, "DELETE_SUCCESS", path_for_permission_check, ERR_SUCCESS);
        }
        else
        {
            uint8_t error_code_to_send = ERR_INTERNAL_ERROR;
            const char *error_msg_to_send = "Server failed to delete file.";
            if (errno == ENOENT)
            {
                error_code_to_send = ERR_FILE_NOT_FOUND;
                error_msg_to_send = "File not found.";
            }
            else if (errno == EACCES)
            {
                error_code_to_send = ERR_PERMISSION_DENIED;
                error_msg_to_send = "Server permission error.";
            }
            // +++ PRE-SEND LOGGING FOR DELETE_REQUEST ERROR +++
            // fprintf(stderr, "[SERVER_SEND_PREP] fd: %d, About to send ERROR for DELETE_REQUEST: type=%u, seq=%u, error_code=%d, message='%s'\\n",
            //         ctx->client_fd, (unsigned int)MSG_TYPE_ERROR, msg_seq, error_code_to_send, error_msg_to_send);
            send_error_message(ctx->client_fd, msg_seq, error_code_to_send, error_msg_to_send);
            add_audit_log(ctx->db, ctx->user_id, "DELETE_FAILED", path_for_permission_check, errno); // Log actual errno
        }
        break;
    }
    case MSG_TYPE_FILE_DOWNLOAD_REQUEST:
    {
        // fprintf(stderr, "[SERVER_SWITCH_TRACE] Matched MSG_TYPE_FILE_DOWNLOAD_REQUEST. fd: %d\\n", ctx->client_fd); // +++ TRACE
        // fprintf(stderr, "[SERVER_MSG] Received MSG_TYPE_FILE_DOWNLOAD_REQUEST (fd: %d)\\n", ctx->client_fd);
        if (!ctx->auth_done)
        {
            send_error_message(ctx->client_fd, msg_seq, ERR_NOT_AUTHENTICATED, "用户未认证");
            break;
        }

        // If a download is already in progress for this client, log it, reset it, and proceed with the new request.
        // This implies a new download request from the same client session supersedes any previous one.
        if (ctx->download_in_progress)
        {
            fprintf(stderr, "[SERVER_DOWNLOAD_WARNING] New download request received while download (ID: %u) was in progress for fd: %d. Resetting previous download state.\n",
                    ctx->current_download_id, ctx->client_fd);
            // No error sent to client here, we just overwrite the state and proceed.
        }

        // Crucially, reset download state before starting a new one (or restarting after a superseded one).
        fprintf(stderr, "[SERVER_DOWNLOAD_STATE] Resetting download state for fd: %d before new/superseding request processing.\n", ctx->client_fd);
        reset_client_download_state(ctx);

        if (msg_data && msg_len == sizeof(file_download_request_t))
        {
            file_download_request_t *req = (file_download_request_t *)msg_data;
            req->path[sizeof(req->path) - 1] = '\0';

            // fprintf(stderr, "[SERVER_DOWNLOAD_REQUEST] Processing download for path: '%s' (fd: %d)\\n", req->path, ctx->client_fd);
            fprintf(stdout, "服务端：处理客户端 (fd: %d) 对路径 '%s' 的文件下载请求。\n", ctx->client_fd, req->path);

            // Construct path for permission check, ensuring it starts with '/'
            char path_for_perm_check[sizeof(req->path) + 2];
            if (req->path[0] == '/')
            {
                strncpy(path_for_perm_check, req->path, sizeof(path_for_perm_check) - 1);
            }
            else
            {
                snprintf(path_for_perm_check, sizeof(path_for_perm_check), "/%s", req->path);
            }
            path_for_perm_check[sizeof(path_for_perm_check) - 1] = '\0';

            fprintf(stdout, "服务端：对用户ID %d 请求下载文件 '%s' (逻辑路径: '%s') 进行权限检查...\n", ctx->user_id, req->path, path_for_perm_check);
            int perm_check_result = check_file_permission(ctx->db, ctx->user_id, path_for_perm_check, OPERATION_READ);

            if (perm_check_result <= 0)
            {
                fprintf(stdout, "服务端：用户ID %d 对文件 '%s' 的下载操作权限不足，请求被拒绝。\n", ctx->user_id, path_for_perm_check);
                send_error_message(ctx->client_fd, msg_seq, ERR_PERMISSION_DENIED, "Permission denied for file download.");
                add_audit_log(ctx->db, ctx->user_id, "DOWNLOAD_REQUEST_DENIED", path_for_perm_check, ERR_PERMISSION_DENIED);
                reset_client_download_state(ctx); // Already called, but good for clarity if path changes
                break;
            }
            fprintf(stdout, "服务端：用户ID %d 对文件 '%s' 的下载权限检查通过。\n", ctx->user_id, path_for_perm_check);

            char user_upload_dir[PATH_MAX];
            const char *base_download_root = "/tmp/sfts_uploads"; // Base directory for all user uploads/downloads
            struct stat st_base_root_dl = {0};

            if (stat(base_download_root, &st_base_root_dl) == -1)
            { // Check if /tmp/sfts_uploads exists
                if (mkdir(base_download_root, 0755) == -1 && errno != EEXIST)
                { // Try to create /tmp/sfts_uploads
                    fprintf(stderr, "[SERVER_DOWNLOAD_ERROR] Failed to create base download directory '%s': %s (fd: %d)\n", base_download_root, strerror(errno), ctx->client_fd);
                    send_error_message(ctx->client_fd, msg_seq, ERR_INTERNAL_ERROR, "服务器内部错误 (base dir creation)");
                    reset_client_download_state(ctx);
                    break;
                }
            }

            snprintf(user_upload_dir, sizeof(user_upload_dir), "%s/%d", base_download_root, ctx->user_id); // Path like /tmp/sfts_uploads/1

            // Ensure user_upload_dir exists
            struct stat dir_stat;
            if (stat(user_upload_dir, &dir_stat) == -1)
            {
                if (mkdir(user_upload_dir, 0755) == -1 && errno != EEXIST) // Try to create /tmp/sfts_uploads/user_id
                {
                    fprintf(stderr, "[SERVER_DOWNLOAD_ERROR] Failed to create user directory '%s': %s (fd: %d)\n", user_upload_dir, strerror(errno), ctx->client_fd);
                    send_error_message(ctx->client_fd, msg_seq, ERR_INTERNAL_ERROR, "服务器内部错误 (user dir creation)");
                    reset_client_download_state(ctx);
                    break;
                }
            }

            char filename_only[256];
            const char *fname_ptr = strrchr(req->path, '/');
            if (fname_ptr)
            {
                strncpy(filename_only, fname_ptr + 1, sizeof(filename_only) - 1);
            }
            else
            {
                strncpy(filename_only, req->path, sizeof(filename_only) - 1);
            }
            filename_only[sizeof(filename_only) - 1] = '\0';

            snprintf(ctx->current_download_server_path, sizeof(ctx->current_download_server_path),
                     "%s/%s", user_upload_dir, filename_only);
            ctx->current_download_server_path[sizeof(ctx->current_download_server_path) - 1] = '\0';

            // fprintf(stderr, "[SERVER_DOWNLOAD_REQUEST] Attempting to open server file: '%s' for download (fd: %d)\\n",
            //         ctx->current_download_server_path, ctx->client_fd);
            fprintf(stdout, "服务端：准备打开服务器物理文件路径: '%s' 进行下载 (fd: %d)。\n", ctx->current_download_server_path, ctx->client_fd);

            struct stat st_file;
            if (stat(ctx->current_download_server_path, &st_file) != 0 || !S_ISREG(st_file.st_mode))
            {
                fprintf(stderr, "[SERVER_DOWNLOAD_ERROR] File not found or not regular: '%s' (fd: %d, errno: %d %s)\n",
                        ctx->current_download_server_path, ctx->client_fd, errno, strerror(errno));
                send_error_message(ctx->client_fd, msg_seq, ERR_FILE_NOT_FOUND, "文件未找到或非普通文件");
                reset_client_download_state(ctx);
                break;
            }

            // TODO: Permission check for file against user_id from database

            ctx->download_file_ptr = fopen(ctx->current_download_server_path, "rb");
            if (!ctx->download_file_ptr)
            {
                fprintf(stderr, "[SERVER_DOWNLOAD_ERROR] Failed to fopen file '%s': %s (fd: %d)\n",
                        ctx->current_download_server_path, strerror(errno), ctx->client_fd);
                send_error_message(ctx->client_fd, msg_seq, ERR_ACCESS_DENIED, "无法打开文件（服务器）");
                reset_client_download_state(ctx);
                break;
            }

            ctx->expected_download_size = st_file.st_size;
            ctx->sent_download_size = 0;
            ctx->download_in_progress = 1; // SETTING IN PROGRESS FLAG
            ctx->current_download_id = get_next_download_id();
            ctx->iv_sent_for_download = 0;

            file_download_response_t resp;
            resp.result = ERR_SUCCESS;
            resp.download_id = ctx->current_download_id;
            resp.size = ctx->expected_download_size;
            resp.block_size = DOWNLOAD_BLOCK_PLAINTEXT_SIZE;

            fprintf(stderr, "[SERVER_DOWNLOAD_REQUEST] Sending download_response. ID: %u, Size: %llu, BlkSize: %u (fd: %d)\n",
                    resp.download_id, (unsigned long long)resp.size, resp.block_size, ctx->client_fd);

            if (send_message(ctx->client_fd, MSG_TYPE_FILE_DOWNLOAD_RESPONSE, msg_seq, &resp, sizeof(resp)) != 0)
            {
                fprintf(stderr, "[SERVER_DOWNLOAD_ERROR] Failed to send download response (fd: %d)\n", ctx->client_fd);
                reset_client_download_state(ctx);
                ctx->marked_for_close = 1;
            }
            else
            {
                // fprintf(stderr, "[SERVER_DOWNLOAD_SUCCESS] Download initiated. ID: %u, File: '%s', Size: %llu (fd: %d). download_in_progress is now %d\\n",
                //         ctx->current_download_id, ctx->current_download_server_path, (unsigned long long)ctx->expected_download_size, ctx->client_fd, ctx->download_in_progress);
                fprintf(stdout, "服务端：文件下载请求 '%s' (用户ID: %d, 下载ID: %u) 已接受，文件大小: %llu B。响应已发送给客户端 (fd: %d)。\n",
                        path_for_perm_check, ctx->user_id, ctx->current_download_id, (unsigned long long)ctx->expected_download_size, ctx->client_fd);
                add_audit_log(ctx->db, ctx->user_id, "DOWNLOAD_REQUEST_ACCEPTED", path_for_perm_check, ERR_SUCCESS);
            }
        }
        else
        {
            fprintf(stderr, "[SERVER_DOWNLOAD_ERROR] Invalid download request data (msg_len %u vs expected %zu) (fd: %d)\n",
                    msg_len, sizeof(file_download_request_t), ctx->client_fd);
            send_error_message(ctx->client_fd, msg_seq, ERR_INVALID_REQUEST, "无效的下载请求数据");
            // No specific download state to reset if request data was bad from the start, as preemptive reset already occurred.
        }
        break;
    }
    case MSG_TYPE_FILE_DOWNLOAD_DATA_REQUEST:
    {
        // fprintf(stderr, "[SERVER_SWITCH_TRACE] Matched MSG_TYPE_FILE_DOWNLOAD_DATA_REQUEST. fd: %d\\n", ctx->client_fd); // +++ TRACE
        // Cast msg_data to req early for logging and validation
        file_download_data_request_t *req = (file_download_data_request_t *)msg_data;

        // Basic validation of req before using it for logging
        if (!msg_data || msg_len < sizeof(file_download_data_request_t)) // Check msg_len against expected struct size
        {
            fprintf(stderr, "[SERVER_DOWNLOAD_ERROR] Invalid or too short download data request message (fd: %d, len: %u, expected_min: %zu)\n",
                    ctx->client_fd, msg_len, sizeof(file_download_data_request_t));
            send_error_message(ctx->client_fd, msg_seq, ERR_INVALID_REQUEST, "Malformed download data request.");
            // No specific download state to reset as it might not have been properly initiated
            break; // Exit case
        }
        // Now it is safer to log using req, though req itself might still be logically invalid (e.g. wrong download_id)
        fprintf(stdout, "服务端：接收到客户端 (fd: %d) 的文件下载数据块请求 (MSG_TYPE_FILE_DOWNLOAD_DATA_REQUEST)，下载ID: %u, 请求块号: %u。\n", ctx->client_fd, req->download_id, req->block_num);

        if (!ctx->auth_done)
        {
            send_error_message(ctx->client_fd, msg_seq, ERR_NOT_AUTHENTICATED, "用户未认证");
            break;
        }
        if (!ctx->download_in_progress)
        {
            fprintf(stderr, "[SERVER_DOWNLOAD_ERROR] Received download data request but no download in progress (fd: %d)\n", ctx->client_fd);
            send_error_message(ctx->client_fd, msg_seq, ERR_INVALID_STATE, "无下载进行中");
            break;
        }
        // file_download_data_request_t *req = (file_download_data_request_t *)msg_data; // Already declared and assigned above
        // if (!req) // Basic null check already implicitly covered by msg_data check if msg_len was okay.
        // {
        //     send_error_message(ctx->client_fd, msg_seq, ERR_INVALID_REQUEST, "无效的下载数据请求.");
        //     break;
        // }

        if (req->download_id != ctx->current_download_id)
        {
            fprintf(stderr, "[SERVER_DOWNLOAD_ERROR] Download ID mismatch (fd: %d, expected: %u, got: %u)\n",
                    ctx->client_fd, ctx->current_download_id, req->download_id);
            send_error_message(ctx->client_fd, msg_seq, ERR_INVALID_STATE, "下载ID不匹配.");
            reset_client_download_state(ctx); // This might be a critical error, reset state.
            break;
        }

        unsigned char plain_buffer[DOWNLOAD_BLOCK_PLAINTEXT_SIZE];
        long offset = (long)req->block_num * DOWNLOAD_BLOCK_PLAINTEXT_SIZE;

        if (fseek(ctx->download_file_ptr, offset, SEEK_SET) != 0)
        {
            fprintf(stderr, "[SERVER_DOWNLOAD_ERROR] fseek failed for file '%s' at offset %ld (fd: %d): %s\n",
                    ctx->current_download_server_path, offset, ctx->client_fd, strerror(errno));
            send_error_message(ctx->client_fd, msg_seq, ERR_INTERNAL_ERROR, "服务器读取文件失败 (seek).");
            reset_client_download_state(ctx);
            break;
        }

        size_t bytes_read = fread(plain_buffer, 1, DOWNLOAD_BLOCK_PLAINTEXT_SIZE, ctx->download_file_ptr);
        if (bytes_read == 0 && ferror(ctx->download_file_ptr))
        {
            fprintf(stderr, "[SERVER_DOWNLOAD_ERROR] fread failed for file '%s' (fd: %d): %s\n",
                    ctx->current_download_server_path, ctx->client_fd, strerror(errno));
            send_error_message(ctx->client_fd, msg_seq, ERR_INTERNAL_ERROR, "服务器读取文件失败 (read).");
            reset_client_download_state(ctx);
            break;
        }

        unsigned char encrypted_buffer[SM4_IV_SIZE + DOWNLOAD_BLOCK_PLAINTEXT_SIZE + SM4_BLOCK_SIZE]; // Max possible size: IV + plaintext + padding
        size_t encrypted_data_len = 0;
        size_t actual_payload_offset_in_encrypted_buffer = 0;

        if (req->block_num == 0 && !ctx->iv_sent_for_download)
        {
            // First block, generate and prepend IV
            if (generate_secure_random_iv(ctx->download_session_iv, SM4_IV_SIZE) != 0)
            { // USING SECURE FUNCTION
                fprintf(stderr, "[SERVER_DOWNLOAD_ERROR] Failed to generate IV for download (fd: %d)\n", ctx->client_fd);
                send_error_message(ctx->client_fd, msg_seq, ERR_CRYPTO_ERROR, "服务器加密初始化失败 (IV gen).");
                reset_client_download_state(ctx);
                break;
            }

            memcpy(encrypted_buffer, ctx->download_session_iv, SM4_IV_SIZE);
            actual_payload_offset_in_encrypted_buffer = SM4_IV_SIZE;
            ctx->iv_sent_for_download = 1;
            fprintf(stdout, "服务端：为下载ID %u (fd: %d) 的首个数据块生成SM4-CBC模式的IV。\n", ctx->current_download_id, ctx->client_fd);
        }
        else if (!ctx->iv_sent_for_download)
        {
            fprintf(stderr, "[SERVER_DOWNLOAD_ERROR] IV not sent for subsequent block (fd: %d, block: %u)\n", ctx->client_fd, req->block_num);
            send_error_message(ctx->client_fd, msg_seq, ERR_INVALID_STATE, "服务器加密状态错误 (IV missing).");
            reset_client_download_state(ctx);
            break;
        }

        size_t current_encryption_output_len = sizeof(encrypted_buffer) - actual_payload_offset_in_encrypted_buffer;
        if (bytes_read > 0)
        {
            fprintf(stdout, "服务端：准备使用SM4-CBC模式加密文件块 %u (明文大小: %zu B) 用于下载ID %u (fd: %d)。\n", req->block_num, bytes_read, ctx->current_download_id, ctx->client_fd);
            if (sm4_cbc_encrypt_data(plain_buffer, bytes_read, ctx->shared_key, ctx->download_session_iv,
                                     encrypted_buffer + actual_payload_offset_in_encrypted_buffer, &current_encryption_output_len) != 0)
            {
                fprintf(stderr, "[SERVER_DOWNLOAD_ERROR] Failed to encrypt download data block %u (fd: %d)\n", req->block_num, ctx->client_fd);
                fprintf(stdout, "服务端：SM4加密文件块 %u (fd: %d) 失败。\n", req->block_num, ctx->client_fd);
                send_error_message(ctx->client_fd, msg_seq, ERR_CRYPTO_ERROR, "服务器加密数据失败.");
                reset_client_download_state(ctx);
                break;
            }
        }
        else
        {
            current_encryption_output_len = 0;
        }
        encrypted_data_len = actual_payload_offset_in_encrypted_buffer + current_encryption_output_len;
        fprintf(stdout, "服务端：SM4加密文件块 %u (fd: %d) 完成，加密后数据长度 (包含IV，若有): %zu B。\n", req->block_num, ctx->client_fd, encrypted_data_len);

        size_t data_msg_struct_size = offsetof(file_download_data_t, data);
        size_t total_msg_to_send_len = data_msg_struct_size + encrypted_data_len;

        file_download_data_t *data_msg = (file_download_data_t *)malloc(total_msg_to_send_len);
        if (!data_msg)
        {
            fprintf(stderr, "[SERVER_DOWNLOAD_ERROR] Failed to allocate memory for download data message (fd: %d)\n", ctx->client_fd);
            send_error_message(ctx->client_fd, msg_seq, ERR_INTERNAL_ERROR, "服务器内存不足.");
            reset_client_download_state(ctx);
            break;
        }

        data_msg->download_id = ctx->current_download_id;
        data_msg->block_num = req->block_num;
        data_msg->data_len = encrypted_data_len;

        ctx->sent_download_size += bytes_read;
        data_msg->is_last = (ctx->sent_download_size >= ctx->expected_download_size);
        if (bytes_read < DOWNLOAD_BLOCK_PLAINTEXT_SIZE && feof(ctx->download_file_ptr))
        { // Check if it was a short read due to EOF
            data_msg->is_last = 1;
        }
        if (bytes_read == 0 && data_msg->is_last == 0 && ctx->sent_download_size < ctx->expected_download_size)
        {
            // If we read 0 bytes, but not expecting to be last, make it last to avoid infinite loop on client if file shrank. Or error out.
            // For now, if bytes_read is 0, and we haven't met expected size, we make it last. Client should verify total size.
            data_msg->is_last = 1;
        }

        if (encrypted_data_len > 0)
        {
            memcpy(data_msg->data, encrypted_buffer, encrypted_data_len);
        }

        fprintf(stdout, "服务端：准备发送SM4加密后的文件块 %u (密文长度 %zu B, 明文 %zu B) 用于下载ID %u，是否最后一块: %d (fd: %d)。已发送明文总量: %llu/%llu B。\n",
                req->block_num, encrypted_data_len, bytes_read, ctx->current_download_id, data_msg->is_last, ctx->client_fd,
                (unsigned long long)ctx->sent_download_size, (unsigned long long)ctx->expected_download_size);

        if (send_message(ctx->client_fd, MSG_TYPE_FILE_DOWNLOAD_DATA, msg_seq, data_msg, total_msg_to_send_len) != 0)
        {
            fprintf(stderr, "[SERVER_DOWNLOAD_ERROR] Failed to send download data block %u (fd: %d)\n", req->block_num, ctx->client_fd);
            free(data_msg);
            reset_client_download_state(ctx);
            ctx->marked_for_close = 1;
            break;
        }
        free(data_msg);

        if (data_msg->is_last)
        {
            fprintf(stdout, "服务端：文件 '%s' (下载ID: %u) 已全部发送给客户端 (fd: %d)，SM4加密传输完成。\n",
                    ctx->current_download_server_path, ctx->current_download_id, ctx->client_fd);
            reset_client_download_state(ctx);
        }
        break;
    }
    case MSG_TYPE_TRANSFER_CANCEL_REQUEST:
    {
        // fprintf(stderr, "[SERVER_SWITCH_TRACE] Matched MSG_TYPE_TRANSFER_CANCEL_REQUEST. fd: %d\\n", ctx->client_fd); // +++ TRACE
        // fprintf(stderr, "[SERVER_MSG] Received MSG_TYPE_TRANSFER_CANCEL_REQUEST (fd: %d)\\n", ctx->client_fd);
        if (!ctx->auth_done)
        {
            send_error_message(ctx->client_fd, msg_seq, ERR_NOT_AUTHENTICATED, "用户未认证");
            break;
        }

        if (msg_data && msg_len >= sizeof(transfer_cancel_request_t))
        {
            transfer_cancel_request_t *cancel_req = (transfer_cancel_request_t *)msg_data;
            uint32_t transfer_id = cancel_req->transfer_id;
            uint8_t transfer_type = cancel_req->type;

            fprintf(stderr, "[SERVER_CANCEL] 收到取消传输请求: ID=%u, 类型=%d (fd: %d)\n",
                    transfer_id, transfer_type, ctx->client_fd);

            transfer_cancel_response_t cancel_resp;
            cancel_resp.transfer_id = transfer_id;
            cancel_resp.result = ERR_SUCCESS; // 默认设为成功

            // 处理上传类型的取消
            if (transfer_type == TRANSFER_TYPE_UPLOAD)
            {
                if (ctx->upload_in_progress && ctx->current_upload_id == transfer_id)
                {
                    fprintf(stderr, "[SERVER_CANCEL] 取消上传: ID=%u (fd: %d)\n", transfer_id, ctx->client_fd);
                    reset_client_upload_state(ctx);
                    add_audit_log(ctx->db, ctx->user_id, "UPLOAD_CANCELLED",
                                  ctx->current_upload_server_path, ERR_SUCCESS);
                }
                else
                {
                    fprintf(stderr, "[SERVER_CANCEL] 上传ID不匹配或无上传进行中: 请求ID=%u, 当前ID=%u (fd: %d)\n",
                            transfer_id, ctx->current_upload_id, ctx->client_fd);
                    cancel_resp.result = ERR_INVALID_STATE;
                }
            }
            // 处理下载类型的取消
            else if (transfer_type == TRANSFER_TYPE_DOWNLOAD)
            {
                if (ctx->download_in_progress && ctx->current_download_id == transfer_id)
                {
                    fprintf(stderr, "[SERVER_CANCEL] 取消下载: ID=%u (fd: %d)\n", transfer_id, ctx->client_fd);
                    reset_client_download_state(ctx);
                    add_audit_log(ctx->db, ctx->user_id, "DOWNLOAD_CANCELLED",
                                  ctx->current_download_server_path, ERR_SUCCESS);
                }
                else
                {
                    fprintf(stderr, "[SERVER_CANCEL] 下载ID不匹配或无下载进行中: 请求ID=%u, 当前ID=%u (fd: %d)\n",
                            transfer_id, ctx->current_download_id, ctx->client_fd);
                    cancel_resp.result = ERR_INVALID_STATE;
                }
            }
            // 未知传输类型
            else
            {
                fprintf(stderr, "[SERVER_CANCEL] 未知传输类型: %d (fd: %d)\n", transfer_type, ctx->client_fd);
                cancel_resp.result = ERR_INVALID_REQUEST;
            }

            // 发送取消响应
            if (send_message(ctx->client_fd, MSG_TYPE_TRANSFER_CANCEL_RESPONSE, msg_seq,
                             &cancel_resp, sizeof(cancel_resp)) != 0)
            {
                fprintf(stderr, "[SERVER_CANCEL] 发送取消响应失败 (fd: %d)\n", ctx->client_fd);
                ctx->marked_for_close = 1;
            }
        }
        else
        {
            fprintf(stderr, "[SERVER_CANCEL] 无效的取消请求数据 (fd: %d)\n", ctx->client_fd);
            send_error_message(ctx->client_fd, msg_seq, ERR_INVALID_REQUEST, "无效的取消传输请求数据");
        }
        break;
    }
    case MSG_TYPE_FILE_DOWNLOAD_ACK:
    {
        // 服务端收到客户端对下载数据块的确认
        // 通常服务器在发送完数据块后已经完成了大部分工作，客户端的ACK主要是为了客户端自身的流程控制
        // 服务器侧可以记录这个ACK，但一般不需要再回复客户端
        // fprintf(stderr, "[SERVER_SWITCH_TRACE] Received MSG_TYPE_FILE_DOWNLOAD_ACK from fd %d, seq %u.\n", ctx->client_fd, msg_seq);
        // 可选: 解析ack内容进行更详细的日志或校验
        if (msg_len >= sizeof(file_download_ack_t))
        {
            file_download_ack_t *ack_msg = (file_download_ack_t *)msg_data;
            fprintf(stderr, "[SERVER_DETAIL] Download ACK details: fd=%d, DownloadID=%u, BlockNum=%u, Result=%u\n",
                    ctx->client_fd, ack_msg->download_id, ack_msg->block_num, ack_msg->result);
            // 这里可以根据ack_msg->result进行一些错误处理或状态更新，如果客户端报告了错误
        }
        else
        {
            // fprintf(stderr, "[SERVER_WARNING] Received MSG_TYPE_FILE_DOWNLOAD_ACK with insufficient data_len %u from fd %d\\n", msg_len, ctx->client_fd);
        }
        // 无需向客户端发送响应
        break;
    }
    // Default case for unhandled messages
    default:
        // +++ DETAILED SWITCH DIAGNOSTIC LOGGING FOR DEFAULT +++
        // fprintf(stderr, "[SERVER_SWITCH_DEBUG_DEFAULT] Entered DEFAULT branch. msg_type was: %u. MSG_TYPE_FILE_LIST_REQUEST is %d. fd: %d\\n",
        //         current_msg_type_for_switch, MSG_TYPE_FILE_LIST_REQUEST, ctx->client_fd);
        // +++ END DETAILED SWITCH DIAGNOSTIC LOGGING FOR DEFAULT +++
        fprintf(stderr, "[SERVER_WARNING] Received unknown message type: %u (fd: %d)\\n", current_msg_type_for_switch, ctx->client_fd); // Use current_msg_type_for_switch
        // +++ PRE-SEND LOGGING FOR DEFAULT BRANCH ERROR +++
        // fprintf(stderr, "[SERVER_SEND_PREP] fd: %d, About to send ERROR for DEFAULT_BRANCH: type=%u, seq=%u, error_code=%d, message='%s'\\n",
        //         ctx->client_fd, (unsigned int)MSG_TYPE_ERROR, msg_seq, ERR_INVALID_REQUEST, "未知消息类型");
        send_error_message(ctx->client_fd, msg_seq, ERR_INVALID_REQUEST, "未知消息类型");
        break;
    }

    if (msg_data)
    {
        free(msg_data);
    }

    // Re-arm EPOLLONESHOT if not marked for close
    // This logic assumes that if marked_for_close is set, the main loop will DEL from epoll.
    // If an error occurred above that set marked_for_close, we should not re-arm.
    if (!ctx->marked_for_close)
    {
        struct epoll_event event;
        event.data.ptr = ctx;
        event.events = EPOLLIN | EPOLLET | EPOLLONESHOT;
        if (epoll_ctl(ctx->epoll_fd, EPOLL_CTL_MOD, ctx->client_fd, &event) == -1)
        {
            perror("process_client_event: epoll_ctl EPOLL_CTL_MOD failed for re-arm");
            ctx->marked_for_close = 1; // Mark for cleanup by main loop
        }
    }
}

// 清理服务端资源
void server_cleanup(int server_fd)
{
    if (server_fd >= 0)
    {
        printf("Closing server listening socket fd %d\n", server_fd);
        close(server_fd);
    }
}

// Thread pool getter for server_main
thread_pool_t *get_server_thread_pool()
{
    return server_thread_pool;
}

void init_server_thread_pool(int min_threads, int max_threads, int queue_size)
{
    if (server_thread_pool == NULL)
    {
        server_thread_pool = thread_pool_create(min_threads, max_threads, queue_size);
        if (server_thread_pool == NULL)
        {
            perror("线程池创建失败 (init_server_thread_pool)");
            // Consider exiting or a more robust error handling
        }
    }
}

void destroy_server_thread_pool()
{
    if (server_thread_pool != NULL)
    {
        thread_pool_destroy(server_thread_pool);
        server_thread_pool = NULL;
    }
}

static void reset_client_download_state(client_context_t *ctx)
{
    if (!ctx)
        return;
    // Use a more specific log prefix for server-side debugging
    fprintf(stderr, "[SERVER_DOWNLOAD_STATE] Attempting to reset download state for fd: %d, current_download_id: %u, in_progress_flag: %d\n",
            ctx->client_fd, ctx->current_download_id, ctx->download_in_progress);

    if (ctx->download_file_ptr)
    {
        fprintf(stderr, "[SERVER_DOWNLOAD_STATE] Closing download_file_ptr for fd: %d, path: '%s'\n", ctx->client_fd, ctx->current_download_server_path);
        fclose(ctx->download_file_ptr);
        ctx->download_file_ptr = NULL;
    }
    ctx->current_download_server_path[0] = '\0';
    ctx->expected_download_size = 0;
    ctx->sent_download_size = 0;
    ctx->download_in_progress = 0;
    // current_download_id is typically set when a new download successfully starts.
    // Resetting it here might be okay, or it might be better to let the new download assignment handle it.
    // For now, let's not reset it to 0 unless a new download truly starts or context is fully cleared.
    // If download_id should be unique per download attempt, then it should be reset or invalidated.
    // Let's reconsider current_download_id resetting later if needed. It's safer to leave it for now if it helps debug.
    // ctx->iv_sent_for_download = 0; // Will be set by the new download if it starts
    // No need to clear download_session_iv itself, it will be overwritten.
    memset(ctx->download_session_iv, 0, SM4_IV_SIZE); // Clear the IV
    ctx->iv_sent_for_download = 0;                    // Reset the flag

    fprintf(stderr, "[SERVER_DOWNLOAD_STATE] Download state reset complete for fd: %d. download_in_progress is now %d\n",
            ctx->client_fd, ctx->download_in_progress);
}

// Placeholder for upload state reset, to be implemented if not already present or if needed for symmetry.
static void reset_client_upload_state(client_context_t *ctx)
{
    if (!ctx)
        return;
    // fprintf(stderr, "[SERVER_UPLOAD_STATE] Attempting to reset upload state for fd: %d, current_upload_id: %u, in_progress_flag: %d\n",
    //         ctx->client_fd, ctx->current_upload_id, ctx->upload_in_progress);
    if (ctx->upload_file_ptr)
    {
        fclose(ctx->upload_file_ptr);
        ctx->upload_file_ptr = NULL;
    }
    ctx->current_upload_server_path[0] = '\0';
    ctx->expected_upload_size = 0;
    ctx->received_upload_size = 0;
    ctx->upload_in_progress = 0;
    ctx->iv_received_for_upload = 0;
    // fprintf(stderr, "[SERVER_UPLOAD_STATE] Upload state reset complete for fd: %d. upload_in_progress is now %d\n",
    //         ctx->client_fd, ctx->upload_in_progress);
}

// For now, this is a placeholder.
static uint32_t g_current_download_id_counter = 0; // Global or part of a server state struct
uint32_t get_next_download_id()
{
    // Consider thread safety if multiple threads can call this simultaneously.
    // For now, assuming it's called sequentially or from a context that handles synchronization.
    return ++g_current_download_id_counter;
}